//
//  CircleScoreView.m
//  wuliangye
//
//  Created by yeeyuntech on 2017/4/8.
//  Copyright © 2017年 jarze. All rights reserved.
//

#import "CircleScoreView.h"
#define DEGREES_TO_RADIANS(degrees) (degrees) / 180.0 * M_PI
#define RGB(r,g,b) [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]

@interface CircleScoreView ()
@property (nonatomic) CGFloat rangeLabelsFontKerning;//字距调整
@property (nonatomic) CGFloat rangeLabelsWidth;

@property (nonatomic) CGFloat rangeScoreWidth;//外环宽度

@property (nonatomic) bool showRangeLabels;//表盘外环显示

@end
@implementation CircleScoreView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
{
    CGRect fullRect;//原盘大小
//    CGRect innerRimRect;
//    CGRect innerRimBorderRect;
//    CGRect faceRect;
    CGRect rangeLabelsRect;//区域文字
    
    CGRect rangeScoreRect;//外环区域
    
    
    
//    CGRect scaleRect;
    CGPoint center;//中心点位置
    CGFloat scaleRotation;//初始旋转角度
//    CGFloat divisionValue;
//    CGFloat subdivisionValue;
//    CGFloat subdivisionAngle;
    double currentValue;//当前值
//    double needleAcceleration;
//    double needleVelocity;
//    NSTimeInterval needleLastMoved;
    UIImage *background;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initialize];
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self initialize];
}

//初始化
- (void)initialize{
    _value = 0.0;
    _minValue = 0.0;
    _maxValue = 320.0;
    currentValue = 0.0;
    
    
    _rangeLabelsFontKerning = 1.0;
    _rangeLabelsWidth = 0.04;
    _showRangeLabels = YES;
    _rangeScoreWidth = 0.1;
    _scaleStartAngle = 30.0;
    _scaleEndAngle = 330.0;
    
    [self initDrawingRects];
    [self initScale];

}
- (void)initDrawingRects
{
    center = CGPointMake(0.5, 0.5);
    fullRect = CGRectMake(0.0, 0.0, 1.0, 1.0);
    
    rangeLabelsRect = CGRectMake(fullRect.origin.x + _rangeScoreWidth/2.0f,
                                 fullRect.origin.y + _rangeScoreWidth/2.0f,
                                 fullRect.size.width - _rangeScoreWidth,
                                 fullRect.size.height - _rangeScoreWidth);

    
    rangeScoreRect = CGRectMake(fullRect.origin.x + _rangeScoreWidth/2.0f,
                                 fullRect.origin.y + _rangeScoreWidth/2.0f,
                                 fullRect.size.width - _rangeScoreWidth,
                                 fullRect.size.height - _rangeScoreWidth);
}

- (void)initScale
{
    //_scaleDivisions  大格数
    //_scaleSubdivisions 每大格中小格数
    
    //初始旋转角度
    scaleRotation = (int)(_scaleStartAngle + 180) % 360;
    
//    //每大格范围值
//    divisionValue = (_maxValue - _minValue) / _scaleDivisions;
//    
//    //每小格范围值
//    subdivisionValue = divisionValue / _scaleSubdivisions;
//    
//    //每小格角度
//    subdivisionAngle = (_scaleEndAngle - _scaleStartAngle) / (_scaleDivisions * _scaleSubdivisions);
}


- (void)drawRect:(CGRect)rect
{
//    [self computeCurrentValue];
    if (background == nil)
    {
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, [UIScreen mainScreen].scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        
        //画图大小比例缩放
        CGContextScaleCTM(context, rect.size.width , rect.size.height);
        [self drawRangeLabels:context];
        background = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    [background drawInRect:rect];
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(context, rect.size.width , rect.size.height);
}


- (void)drawRangeLabels:(CGContextRef)context
{
    CGContextSaveGState(context);
    //旋转角度
    [self rotateContext:context fromCenter:center withAngle:DEGREES_TO_RADIANS(90 + _scaleStartAngle)];
    CGFloat maxAngle = _scaleEndAngle - _scaleStartAngle;
    CGFloat lastStartAngle = 0.0f;
    for (int i = (int)(_rangeValues.count - 1); i >=0; i --   )
    {
        float value = ((NSNumber*)[_rangeValues objectAtIndex:i]).floatValue;
        float valueAngle = (value - _minValue) / (_maxValue - _minValue) * maxAngle;

        UIBezierPath *path = [UIBezierPath bezierPath];
        [path addArcWithCenter:center radius:rangeScoreRect.size.width / 2.0 startAngle:DEGREES_TO_RADIANS(lastStartAngle) endAngle:DEGREES_TO_RADIANS(valueAngle) clockwise:YES];
        UIColor *color = _rangeColors[i];
        [color setStroke];
        if (i == [_rangeValues count] -1) {
            [path setLineCapStyle:kCGLineCapRound];
        }else{
            [path setLineCapStyle:kCGLineCapButt];
        }
        path.lineWidth = _rangeScoreWidth;
        [path stroke];
        if (_showRangeLabels) {
            //画字
            [self drawStringAtContext:context string:(NSString*)_rangeLabels[i] withCenter:center radius:rangeScoreRect.size.width / 2.0 startAngle:DEGREES_TO_RADIANS(lastStartAngle) endAngle:DEGREES_TO_RADIANS(valueAngle)];
        }
        lastStartAngle = valueAngle;
    }
    
    CGContextRestoreGState(context);
}

//画字符串
- (void) drawStringAtContext:(CGContextRef) context string:(NSString*)text withCenter:(CGPoint)center_ radius:(CGFloat)radius startAngle:(CGFloat)startAngle endAngle:(CGFloat)endAngle
{
    //    苹果设置一个保存图形上下文的栈,来随时存储当前你的图形上下文
    //    通过
    //    CGContextSaveGState(context)；
    //    来保存(推入)图形上下文到栈顶
    //    在绘制(渲染之后),通过
    //    CGContextRestoreGState(context);
    //    来更新(将之前入栈的图形上下文状态出栈,将当前的图形上下文状态入栈)图形上下到栈顶
    //    注意:这两个代码一般成对出现, 这样既保护了图形上下文状态的唯一性,也方便了在需要的地方修改图形上下状态
    CGContextSaveGState(context);
    NSDictionary* stringAttrs = @{ NSFontAttributeName : [UIFont systemFontOfSize:0.05], NSForegroundColorAttributeName : [UIColor redColor] };
    //文字长度
    CGSize textSize = [text sizeWithAttributes:stringAttrs];
    //圆周长
    float perimeter = 2 * M_PI * radius;
    //字幅度角
    float textAngle = textSize.width / perimeter * 2 * M_PI * _rangeLabelsFontKerning;
    
    
//    float offset = ((endAngle - startAngle) - textAngle) / 2.0;//文字在区域中间
    float offset = (endAngle - startAngle) - textAngle/2.0;
    float letterPosition = 0;
    
    //旋转字符串到计算的位置
    [self rotateContext:context fromCenter:center withAngle:startAngle + offset];

    //画每个字符
    for (int index = 0; index < [text length]; index++)
    {
        
        //取出字符
        NSRange range = {index, 1};
        NSString* letter = [text substringWithRange:range];
//        NSAttributedString* attrStr = [[NSAttributedString alloc] initWithString:letter attributes:stringAttrs];
        
        NSLog(@"%@*****", letter);
        
        CGSize charSize = [letter sizeWithAttributes:stringAttrs];
        
        //字符位置长度
        letterPosition += (charSize.width / 2);
        //        - kerning;
        
        float angle = (letterPosition / perimeter * 2 * M_PI) * _rangeLabelsFontKerning;
        
        //字符坐标
        CGPoint letterPoint = CGPointMake((radius) * cos(angle) + center_.x, (radius) * sin(angle) + center_.y);
        
        //字符旋转
        CGContextSaveGState(context);
        //        移动函数平移变换根据我们指定的x, y轴的值移动坐标系统的原点。
        CGContextTranslateCTM(context, letterPoint.x, letterPoint.y);
        //旋转
        CGAffineTransform rotationTransform = CGAffineTransformMakeRotation(angle + M_PI_2);
        CGContextConcatCTM(context, rotationTransform);
        CGContextTranslateCTM(context, -letterPoint.x, -letterPoint.y);
        //字符位置原点在左上角，调整到中心位置
        [letter drawAtPoint:CGPointMake(letterPoint.x - charSize.width/2 , letterPoint.y - charSize.height / 2) withAttributes:stringAttrs];
        CGContextRestoreGState(context);
        //保存字符结束的位置
        letterPosition += charSize.width / 2;
    }
    CGContextRestoreGState(context);
}

// 旋转
- (void)rotateContext:(CGContextRef)context fromCenter:(CGPoint)center_ withAngle:(CGFloat)angle
{
    CGContextTranslateCTM(context, center_.x, center_.y);
    CGContextRotateCTM(context, angle);
    CGContextTranslateCTM(context, -center_.x, -center_.y);
}

//取各色区颜色
- (UIColor*)rangeColorForValue:(float)value
{
    NSInteger length = _rangeValues.count;
    for (int i = 0; i < length - 1; i++)
    {
        if (value < [_rangeValues[i] floatValue])
            return _rangeColors[i];
    }
    if (value <= [_rangeValues[length - 1] floatValue])
        return _rangeColors[length - 1];
    return nil;
}
@end
